#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include "log.hpp"
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string>
#define NUM 1024
namespace client
{
    using namespace std;
    class TcpClient
    {
    public:
        TcpClient(const string &ip, const uint16_t &port)
            : _sock(-1), _serverip(ip), _serverport(port)
        {
        }
        void initClient()
        {
            // 1.创建套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                cerr << "socket create error" << endl;
            }
            // 2.tcp的客户端要不要bind?要不要显式bind port让OS随机指定
            // 3.不需要listen
            // 4.不需要accept
            // 5.要发起链接
        }
        void Start()
        {
            struct sockaddr_in server;
            // bzero(&server,sizeof server);
            memset(&server, 0, sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
            {
                cerr << "socket connect error" << endl;
            }
            else
            {
                string msg;
                while (true)
                {
                    cout << "Enter# ";
                    getline(cin, msg);
                    write(_sock, msg.c_str(), msg.size());

                    char buffer[NUM];
                    int n = read(_sock, buffer, sizeof(buffer) - 1);
                    if (n > 0)
                    {
                        // 当字符串
                        buffer[n] = 0;
                        cout << "Server回显# " << buffer << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~TcpClient()
        {
            if (_sock >= 0)
                close(_sock);
        }

    private:
        int _sock;
        string _serverip;
        uint16_t _serverport;
    };

}